<template>
  <div>
    <a-modal :open='props.open' :width="props.modelInfo && props.modelInfo.width ? props.modelInfo.width : '900px'"
      :title="props.modelInfo && props.modelInfo.title ? props.modelInfo.title : 'Basic Modal'" @ok='handleOk'
      okText='保存' :confirmLoading='modelConfig.confirmLoading' :destroyOnClose='modelConfig.destroyOnClose'
      @cancel='handleCancel'>
      <template #footer>
        <a-button key='back' @click='handleCancel'>取消</a-button>
        <a-button key='submit' type='primary' :loading='loading' @click='handleOk'>保存</a-button>
      </template>
      <a-form ref='formRef' name='MembershipConfigurationForm' class='ant-advanced-search-form' :model='formState'
        @finish='onFinish' @finishFailed='onFinishFailed' :rules='rulesRef' :label-col='labelCol'
        :wrapper-col='wrapperCol'>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['membershipName'].name" :label="labelMap['membershipName'].label">
              <a-input v-model:value='formState.membershipName'
                :placeholder="'请填写' + labelMap['membershipName'].label"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['currentPrice'].name" :label="labelMap['currentPrice'].label">
              <a-input v-model:value='formState.currentPrice'
                :placeholder="'请填写' + labelMap['currentPrice'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['originalPrice'].name" :label="labelMap['originalPrice'].label">
              <a-input v-model:value='formState.originalPrice'
                :placeholder="'请填写' + labelMap['originalPrice'].label"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['status'].name" :label="labelMap['status'].label">
              <a-select v-model:value="formState.status">
                <a-select-option :value="true">有效</a-select-option>
                <a-select-option :value="false">失效</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['membership'].name" :label="labelMap['membership'].label">
              <a-input v-model:value='formState.membership'
                :placeholder="'请填写' + labelMap['membership'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang='ts' setup>
import { MembershipConfigurationDetail } from './membershipConfigurationDetailTs';
import {
  getMembershipConfigurationDetail,
  addOrEditMembershipConfiguration,
} from '@/api/membershipInfo/membershipConfiguration/membershipConfigurationTs';
import { message, FormInstance } from 'ant-design-vue';
import { dictInfo } from "@/views/commonInfo/dictInfo/dictInfoListTs";
import { getDictList } from "@/api/commonInfo/dictInfo/dictInfoTs";
import { ModelInfo } from '../membershipConfigurationListTs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const labelMap = ref<any>(
  {
    membershipName: { name: 'membershipName', label: '会员名称' },
    currentPrice: { name: 'currentPrice', label: '当前价格' },
    originalPrice: { name: 'originalPrice', label: '原始价格 ' },
    status: { name: 'status', label: '状态' },
    membership: { name: 'membership', label: '会员类型' },
  });

const rulesRef = reactive({
  membershipName: [
    {
      required: true,
      message: '会员名称 (如: 月会员、季会员、年会员)不能为空！',
    },
  ],
  currentPrice: [
    {
      required: true,
      message: '当前价格不能为空！',
    },
  ],
  status: [
    {
      required: true,
      message: '状态: 0=禁用, 1=启用不能为空！',
    },
  ],
  membership: [
    {
      required: true,
      message: '会员类型(month、quarter、year)不能为空！',
    },
  ],
});

const modelConfig = {
  confirmLoading: true,
  destroyOnClose: true,
};

interface Props {
  open?: boolean;
  modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<MembershipConfigurationDetail>({});

let statusList = ref<dictInfo[]>([]);

const getDictInfoList = () => {
  getDictList("is_valid").then((res) => {
    if (res.code == "200") {
      statusList.value = res.data.filter(
        (item: { belongTo: string }) => item.belongTo == "is_valid"
      );
    } else {
      message.error((res && res.message) || "查询列表失败！");
    }
  });
}

const emit = defineEmits(['handleOk', 'handleCancel']);

const handleOk = (): void => {
  loading.value = true;
  if (formRef.value) {
    formRef.value.validateFields().then(
      () => saveMembershipConfigurationManager()).catch(() => {
        loading.value = false;
      });
  }
};

const handleCancel = (): void => {
  emit('handleCancel', false);
};

//保存会员配置表信息
const saveMembershipConfigurationManager = (): void => {
  let method = '';
  if (formState.value.id) {
    method = 'put';
  } else {
    method = 'post';
  }
  addOrEditMembershipConfiguration(method, formState.value)
    .then((res) => {
      if (res.code == '200') {
        message.success((res && res.message) || '保存成功！');
        emit('handleOk', false);
      } else {
        message.error((res && res.message) || '保存失败！');
      }
      formState.value = {};
    })
    .catch((error: any) => {
      message.error(error?.message || "查询失败！");
    }).finally(() => {
      loading.value = false;
    });
}

const onFinish = (values: any): void => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
  console.log('Failed:', errorInfo);
};

const init = (): void => {
  getDictInfoList();
  if (props.modelInfo) {
    if (props.modelInfo.id) {
      getMembershipConfigurationDetail(props.modelInfo.id)
        .then((res) => {
          if (res.code == '200') {
            formState.value = res.data;
            modelConfig.confirmLoading = false;
          } else {
            message.error((res && res.message) || '查询失败！');
          }
        })
        .catch((error: any) => {
          message.error(error?.message || "查询失败！");
        });
    } else {
      modelConfig.confirmLoading = false;
      formState.value = {
        status: true,
      };
    }
  }
}

watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      init();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang='scss' scoped>
@import '@/style/index.scss';
</style>